package com.softer.chengxin.common.config;

import com.softer.chengxin.common.domin.Common;
import com.softer.chengxin.common.enums.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 异常处理
 *
 * @author Gong Zhiyang
 * @date 2018/9/26
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map handle(Exception e) {
        //记录错误日志
        log.error("错误信息:()", e.getMessage(), e);
        Map map = new HashMap(5);
        if (e instanceof DataIntegrityViolationException) {
            map.put("data", "201");
            map.put("message", "操作失败，请检查关联数据！");
            return map;
        }
        if (e instanceof CourseException) {
            CourseException courseException = (CourseException) e;

            map.put("data", courseException.getData());
            map.put("message", courseException.getMessage());
            return map;
        }
        //校验失败返回
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {

                map.put("data", -1);
                map.put("message", item.getMessage());
                return map;
            }
        } else {
            e.printStackTrace();
            map.put("data", ResultEnum.FAIL.getCode());
            map.put("message", Common.OPERATE_FAIL);
        }
        return map;
    }

}